// pages/grant/grant.js
const api = require('../../utils/api.js');
const {request ,loginApi} = require('../../utils/api.js');
import { ASSETS_BASE_URL, UPLOAD_BASE_URL } from '@/utils/config';
var app = new getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navH:"",
    user:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      navH: app.globalData.navHeight
    })
  },
  formSubmit(e){
    const nickName = e.detail.value.nickname
    if(!this.data.user.headimgurl){
      wx.showToast({
        title: '请授权更新头像',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if(!nickName){
      wx.showToast({
        title: '请授权更新昵称',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    wx.showLoading({
      title: '',
    })
    request('/member_info_set', 'POST', {
      member_id: this.data.user.member_id,
      nickname: nickName,
      headimgurl: this.data.user.headimgurl
    }).then(async res => {
      console.log(res)
      wx.hideLoading()
      if (res.data.code != 200) {
        wx.showToast({
          title: res.data.msg,
          icon: 'error',
          duration: 2000
        })
        return;
      }
      wx.showToast({
        title: res.data.msg,
        icon: 'success',
        duration: 2000
      })
      let a = await api.loginApi.wxMiniAppLogin()
      wx.navigateBack({
        delta: 1
      })
    })
    // do something
  },
  bindgetphonenumber(e) {
    if(!this.data.user.id){
      wx.showToast({
        title: '请先点击用户信息更新授权',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var detail = e.detail
    if (!detail.iv) {
      return;
    }
    wx.login({
      success: res => {
        var obj = {
          code:res.code,
          iv: detail.iv,
          encryptedData: detail.encryptedData
        }
        api.request('phone_get', 'POST', obj).then( async res => {
          var user = api.loginApi.cache('user')
          let params={
            member_id:user.member_id,
            phone:res.data.data.phoneNumber
          }
          api.request('phone_set', 'POST', params).then(async ()  => {
            await api.loginApi.wxMiniAppLogin(res.data.data.phoneNumber)
            wx.navigateBack({
              delta: 1
            })
            
          })
        })
      }
    })
  },
  onChooseAvatar(e) {
    console.log(e)
    const that = this
    wx.uploadFile({
      url: UPLOAD_BASE_URL + '/pic_uploads/name/file',
      header:{ "Content-Type":"multipart/form-data"},//类型
      filePath: e.detail.avatarUrl,
      name: 'file',
      success: function(data) {
        that.setData({
          'user.headimgurl': ASSETS_BASE_URL + data.data
        })
        console.log(ASSETS_BASE_URL + data.data);
        // 处理返回的数据
      },
      fail: function(err) {
        console.error('upload fail:', err);
      }
    });
  },
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.login({
          success: re => {
            var data = {
              code: re.code,
              nickname: res.userInfo.nickName,
              headimgurl: res.userInfo.avatarUrl
            }
            this.updataUserInfo(data)
          }
        })
      }
    })
      
  },
  updataUserInfo(data) {
    api.request('save_wechat_member', 'POST', data).then(res => {
      if (res.data.code == 200) {
        api.loginApi.cache('user', res.data.data)
        this.setData({
          user: res.data.data
        })
        if (res.data.data.member.phone) {
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: '授权用户信息成功，请授权手机号快捷登录',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let userInfo = wx.getStorageSync('user')
    if (userInfo && userInfo.id) {
      this.setData({
        user: userInfo
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})